package com.yx.customized;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.SweepGradient;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;

import java.text.DecimalFormat;

/**
 * Created : Yx
 * Time : 2019/12/5 14:03
 * Describe :
 */
public class CircleProgressBar extends View {
    private RectF mWheelRect = new RectF();//矩形类
    //圆分三层
    private Paint mDefaultWheelPaint;//底部圆环画笔
    private Paint mCenterWheelPaint;//中间圆环画笔
    private Paint mFinishWheelPaint;//最上层圆画笔
    //圆中间文字分三层：上  中   下 （上:步数，中:数值，下:标签）
    private Paint mTitlePaint, mStepPaint, mTargetPaint;
    private float mCircleStrokeWidth;//圆的粗细
    private int mMaxStepNum;// 默认最大数值（进度）
    private int mStepNum;//当前Set过来的数值（进度）
    private float mTitleY, mStepY, mTargetY;//圆中间文字Y坐标
    private int[] progressColor;//渐变色 ，色值数组


    private float mSweepAnglePer;//（根据Set过来的数值计算出需要绘制的圆度数）最上层圆当前度数°最大360°
    private float mPercent;//当前设置的数值与最大数值的百分比
    private int mCurrStepNum;//mCurrStepNum数值
    private float pressExtraStrokeWidth;
    private BarAnimation mAnim;
    private DecimalFormat mDecimalFormat = new DecimalFormat("#.0");// 格式为保留小数点后一位
    public static String GOAL_STEP;
    public static String PERCENT;//percent


    public CircleProgressBar(Context context) {
        super(context);
        init(null, 0);
    }

    public CircleProgressBar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(attrs, 0);
    }

    public CircleProgressBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(attrs, defStyle);
    }


    private void init(AttributeSet attrs, int defStyle) {
        /**
         * 最底部圆环
         */
        mDefaultWheelPaint = new Paint();
        mDefaultWheelPaint.setColor(Color.rgb(243, 243, 243));//#F3F3F3
        mDefaultWheelPaint.setStyle(Paint.Style.STROKE);
        mDefaultWheelPaint.setStrokeCap(Paint.Cap.ROUND);
        mDefaultWheelPaint.setAntiAlias(true);


        /**
         * 中间层圆环
         */
        mCenterWheelPaint = new Paint();
        mCenterWheelPaint.setColor(Color.rgb(227, 238, 255));//E3EEFF
        mCenterWheelPaint.setStyle(Paint.Style.STROKE);
        mCenterWheelPaint.setStrokeCap(Paint.Cap.ROUND);
        mCenterWheelPaint.setAntiAlias(true);

        /**
         * 最上层圆环
         */
        mFinishWheelPaint = new Paint();
        mFinishWheelPaint.setColor(Color.argb((int) 255, 100, 113, 205));//四个0为透明；最上层初始颜色#6471CD
        mFinishWheelPaint.setStyle(Paint.Style.STROKE);// 空心
        mFinishWheelPaint.setStrokeCap(Paint.Cap.ROUND);// 圆角画笔
        mFinishWheelPaint.setAntiAlias(true);// 去锯齿

        /**
         * 上标题
         */
        mTitlePaint = new Paint();
        mTitlePaint.setAntiAlias(true);
        mTitlePaint.setColor(Color.BLACK);

        /**
         * 中数值
         */
        mStepPaint = new Paint();
        mStepPaint.setAntiAlias(true);
        mStepPaint.setColor(Color.BLACK);

        /**
         * 下标签
         */
        mTargetPaint = new Paint();
        mTargetPaint.setAntiAlias(true);
        mTargetPaint.setColor(Color.BLACK);

        /**
         * 动画
         */
        mAnim = new BarAnimation();

        /**
         * 初始渐变色
         */
        progressColor = new int[]{Color.parseColor("#1A1A1A"),
                Color.parseColor("#FF729A"),
                Color.parseColor("#FF583A"),
                Color.parseColor("#4081F1"), Color.TRANSPARENT};
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
        int width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
        int min = Math.min(width, height);// 获取View最短边的长度
        setMeasuredDimension(min, min);// 强制改View为以最短边为长度的正方形
        mCircleStrokeWidth = getTextScale(dpToPx(15), min);// 圆弧的宽度
        pressExtraStrokeWidth = getTextScale(10, min);// 圆弧离矩形的距离（等同于布局中View的Padding）
        mWheelRect.set(mCircleStrokeWidth + pressExtraStrokeWidth, mCircleStrokeWidth + pressExtraStrokeWidth,
                min - mCircleStrokeWidth - pressExtraStrokeWidth, min - mCircleStrokeWidth - pressExtraStrokeWidth);// 设置矩形
        mTitlePaint.setTextSize(getTextScale(60, min));
        mStepPaint.setTextSize(getTextScale(120, min));
        mTargetPaint.setTextSize(getTextScale(40, min));
        mTitleY = getTextScale(170, min);
        mStepY = getTextScale(300, min);
        mTargetY = getTextScale(380, min);
        mFinishWheelPaint.setStrokeWidth(mCircleStrokeWidth);
        mCenterWheelPaint.setStrokeWidth(mCircleStrokeWidth);
        mDefaultWheelPaint.setStrokeWidth(mCircleStrokeWidth - getTextScale(2, min));
        mDefaultWheelPaint.setShadowLayer(getTextScale(10, min), 0, 0, Color.rgb(127, 127, 127));// 设置阴影
    }


    private int dpToPx(int dp) {
        float scale = Resources.getSystem().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    /**
     * 根据控件的大小改变绝对位置的比例
     *
     * @param n
     * @param m
     * @return
     */
    public float getTextScale(float n, float m) {
        return n / 500 * m;
    }


    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        //参一：oval 参数的作用是：定义的圆弧的形状和大小的范围  参二：设置圆弧是从哪个角度来顺时针绘画的   参三：是设置圆弧扫过的角度   参四：设置我们的圆弧在绘画的时候，是否经过圆形
        canvas.drawArc(mWheelRect, 0, 359, false, mDefaultWheelPaint);
        canvas.drawArc(mWheelRect, 0, 359, false, mCenterWheelPaint);
        canvas.drawArc(mWheelRect, -90, mSweepAnglePer, false, mFinishWheelPaint);

        //上标题
        canvas.drawText("步数", mWheelRect.centerX() - (mTitlePaint.measureText("步数") / 2), mTitleY,
                mTitlePaint);
        //中数值
        canvas.drawText(mCurrStepNum + "", mWheelRect.centerX() - (mStepPaint.measureText(String.valueOf(mCurrStepNum)) / 2), mStepY,
                mStepPaint);
        //下标签
        String description = "";
        float percent = getPercent();
        if (percent > 0.5) {
            description = "严重污染";
        } else if (percent < 0.5) {
            description = "中等污染";
        } else {
            description = "普通污染";
        }
        canvas.drawText(description, mWheelRect.centerX() - (mTargetPaint.measureText(description) / 2), mTargetY, mTargetPaint);
        SweepGradient sweepGradient = new SweepGradient(mWheelRect.centerX(), mWheelRect.centerY(), progressColor, null);
        mFinishWheelPaint.setShader(sweepGradient);
    }

    public float getPercent() {
        return mPercent;
    }

    /**
     * 设置渐变色 颜色数组
     *
     * @param progressColor
     */
    public void setProgressColor(int[] progressColor) {
        this.progressColor = progressColor;
        postInvalidate();
    }


    /**
     * 进度条动画
     * 每次系统调用这个方法时， 改变mSweepAnglePer，mPercent，stepnumbernow的值，
     * 然后调用postInvalidate()不停的绘制view。
     */
    public class BarAnimation extends Animation {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {//自定义动画，通过最下面update方法设置动画持续时间
            //super.applyTransformation(interpolatedTime, t);
            //当前百分比mPercent
            mPercent = Float.parseFloat(mDecimalFormat.format(mStepNum * 100f / mMaxStepNum));// 将浮点值四舍五入保留一位小数
            if (mPercent > 100.0f) {
                mPercent = 100.0f;
            }
            PERCENT = String.valueOf(mPercent);//字符串记录，未使用
            mSweepAnglePer = mStepNum * 360 / mMaxStepNum;//最上层圆当前度数°最大360°
            mCurrStepNum = mStepNum;
            requestLayout();//会导致调用measure()过程 和 layout()过程
            //postInvalidate();//请求重绘View树，即draw()过程，假如视图发生大小没有变化就不会调用layout()过程
        }
    }


    /**
     * 设置最大进度值
     *
     * @param stepNum
     */
    public void setMaxStepNum(int stepNum) {
        mMaxStepNum = stepNum;
        GOAL_STEP = String.valueOf(mMaxStepNum);
    }


    /**
     * 更新当前数值（包括进度）和设置一圈动画时间
     *
     * @param stepCount
     * @param time
     */
    public void update(int stepCount, int time) {
        this.mStepNum = stepCount;
        mAnim.setDuration(time);
        // setAnimationTime(time);
        this.startAnimation(mAnim);
    }

    /**
     * 设置动画时间
     *
     * @param time
     */
    public void setAnimationTime(int time) {
        mAnim.setDuration(time * mStepNum / mMaxStepNum);// 按照比例设置动画执行时间
    }


}
